use fastblur::gaussian_blur as fast_blur;
use num;
use photon_rs::PhotonImage;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn special_equalize_with_cache(
    photon_image: &mut PhotonImage,
    pixels: Vec<u8>,
    pixels_2: Vec<u8>,
) {
    let width = photon_image.width;
    let height = photon_image.height;
    for y in 0..height {
        for x in 0..width {
            let pixel_idx = (width * y + x) as usize;
            let idx = pixel_idx << 2;
            let mut b = pixels[pixel_idx] as i32 * 30 - pixels_2[pixel_idx] as i32 * 29;
            b = num::clamp(b, 0, 255);
            photon_image.modify_pixel_in_place(idx, b as u8);
            photon_image.modify_pixel_in_place(idx + 1, b as u8);
            photon_image.modify_pixel_in_place(idx + 2, b as u8);
        }
    }
}

#[wasm_bindgen]
pub fn special_equalize(photon_image: &mut PhotonImage) {
    let width = photon_image.width;
    let height = photon_image.height;

    let mut pixels = vec![0; (width * height) as usize];
    let mut pixels_2 = vec![0; (width * height) as usize];
    let mut i1: usize = 0;
    let mut i2: usize = 0;
    let length = (width * height * 4) as usize;
    while i2 < length {
        pixels[i1] = photon_image.get_pixel_value(i2);
        pixels_2[i1] = photon_image.get_pixel_value(i2);
        i1 += 1;
        i2 += 4;
    }
    fast_blur(&mut pixels, width as usize, height as usize, 1.0);
    fast_blur(&mut pixels_2, width as usize, height as usize, 4.0);
    for y in 0..height {
        for x in 0..width {
            let pixel_idx = (width * y + x) as usize;
            let idx = pixel_idx << 2;
            let mut b = pixels[pixel_idx] as i32 * 30 - pixels_2[pixel_idx] as i32 * 29;
            b = num::clamp(b, 0, 255);
            photon_image.modify_pixel_in_place(idx, b as u8);
            photon_image.modify_pixel_in_place(idx + 1, b as u8);
            photon_image.modify_pixel_in_place(idx + 2, b as u8);
        }
    }
}
